<style lang="scss" src="./index.scss"></style>
<template>
    <div class="ask-image-box">
        <img class="ask-image__inner" v-bind="$attrs" :src="currentSrc" />
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, toRef } from 'vue';
import errorSrc from "@/assets/error.svg";
export default defineComponent({
    props: {
        src: {
            type: String,
            default: ''
        },
        errorSrc: {
            type: String,
            default: ''
        },
        loadSrc: {
            type: String,
            default: ''
        }
    },
    setup(props, { emit }) {
        const currentSrc = ref('');
        const src = toRef(props, 'src');
        const onLoad = (e: Event) => {
            currentSrc.value = props.src;
            emit("load", e);
        };
        const onError = (e: string | Event) => {
            currentSrc.value = props.errorSrc || errorSrc;
            emit("error", e);
        };
        watch(src, (now) => {
            if (!now) {
                return;
            }
            currentSrc.value = props.loadSrc || errorSrc;
            const img = new Image();
            img.src = props.src;
            img.onload = e => {
                onLoad(e);
            };
            img.onerror = e => {
                onError(e);
            };
        }, {
            immediate: true
        });
        return {
            currentSrc
        };
    }
});
</script>
